'''
Created on 2010/4/29

@author: Daniel
'''
from lxml import etree
from StringIO import StringIO
from boxscore import BoxScore

class ParserScoreboard:
    """Parser http://sports.yahoo.com/mlb/scoreboard?d=%date
    """
    def __init__(self, html):
        """
        @param html: html 
        """        
        self.root = etree.parse(StringIO(html), etree.HTMLParser())
        self.gameList = []
        self.gidList = []
    
    def processGame(self, node):
        """process game
        @param node: node of the preprocess game 
        @return: BoxScore(boxScore, info)
        """
        def getBoxScore(subNode):
            """ process box Score
            @param subNode: node of the boxScore
            @return: {'Title':title, 'Away':away, 'Home':home} 
            """
            def getTeamScore(subSubNode):
                """process team score
                @param subSubNode: node of the team
                @return: list 
                """
                score = []
                team = subSubNode.xpath('td[@class="yspscores team"]/b/a')[0].text
                score.append(team)
                for item in subSubNode.xpath('td[@class="yspscores"]'):
                    score.append(item.text)
                for item in subSubNode.xpath('td[@class="ysptblclbg6"]/span'):
                    score.append(item.text)
                return score
            
            count = len(subNode.xpath('tr[2]/td[@class="yspscores"]')) - 4
            title = 'Final', [i+1 for i in range(count)], 'H', 'R', 'E'            
            away = getTeamScore(subNode.xpath('tr[@class="ysptblclbg5"]')[0])
            home = getTeamScore(subNode.xpath('tr[@class="ysptblclbg5"]')[1])
            return {'Title':title, 'Away':away, 'Home':home}
        
        def getInfo(subNode):
            """process info
            @param subNode: node of the info
            @return: {'WP':(), 'LP':(), ['SV':()], ['HR':[(team,player,count),...]]} 
            """
            info = {}
            pitcherNode = subNode.xpath('tr/td[@class="yspscores"]/table/tr/td/table/tr/td/span[@class="yspscores"]/a')            
            info['WP'] = pitcherNode[0].text, pitcherNode[0].tail.split('\n')[0].strip()
            i = 1
            if len(pitcherNode) == 3:
                info['SV'] = pitcherNode[i].text, pitcherNode[i].tail.strip()
                i += 1
            info['LP'] = pitcherNode[i].text, pitcherNode[i].tail.strip()   
            fielderNode = subNode.xpath('tr/td[@class="yspscores"]/table/tr[2]/td')
            if len(fielderNode[0]) != 0:
                team = fielderNode[0].text.split(':')[1].split('-')[0].strip()
                p = []
                for a in fielderNode[0]:
                    p.append((team, a.text, a.tail.split(',')[0].strip()))
                    if len(a.tail.split('-')) >= 2:
                        team = a.tail.split(',')[1].split('-')[0].strip()
                info['HR'] = p 
            return info
            
        return BoxScore(getBoxScore(node[0]), getInfo(node[1]))   
        
    def getGame(self):
        """call process all game and return gameList
        @return: gameList = [BoxScore(), ...]
        """
        if len(self.gameList) == 0:
            node = self.root.xpath('//*[@id="ysp-leaguescoreboard"]/div/table/tr/td/table/tr/td/table/tr/td/table/tr/td')
            self.gameList = [self.processGame(subNode) for subNode in node]
        return self.gameList
        
    def getGidList(self):
        """get all game id and return gidlist
        @return: gidList = ['', ...]
        """
        if len(self.gidList) == 0:
            node =self.root.xpath('//div[@id="ysp-leaguescoreboard"]/div/table//tr/td/table//tr/td/table//tr/td/table//tr/td/table/tr/td/a[@class="yspmore"]')
            for subNode in node[0::2]:
                self.gidList.append(subNode.attrib['href'].split('=')[1])
        
        return self.gidList
    
        
    
if __name__ == '__main__':
    from urllib import urlopen
    date = '2010-05-03'
    url = "http://sports.yahoo.com/mlb/scoreboard?d=%s" % date    
    f = urlopen(url)
    html = f.read()
    p = ParserScoreboard(html)
    boxscore = []
    print date, "U.S.A Date"
    for game in p.getGame():
        game.showGame()
        print
    
    #boxscore = p.getGidList()
    
    """
    print 'American League'
    for game in p.alGame():
        game.showBoxScore()
        boxscore.append(game.gid)
        print
    print 'National League'
    for game in p.nlGame():
        game.showBoxScore()
        boxscore.append(game.gid)
        print
    """
    """ BoxScore-> http://sports.yahoo.com/mlb/boxscore?gid=%s' % gid"""
    
    """
    import os
    from boxscore2 import BoxScore2
    for g in boxscore:
        p = BoxScore2(g)
        p.run()
        p.showBoxScore()
        raw_input()
        os.system('cls')
    """
    